<template>
  <div>
    <el-dialog
      title="子设备"
      :visible.sync="dialogVisible"
      width="65%"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="common-container">
        <div class="header">
          <div class="header_left">
            <el-input
              v-model="searchForm.imei"
              clearable
              @clear="clearImei"
              placeholder="请输入设备编码"
              size="small"
              style="width: 280px"
              maxlength="50"
              oninput="value=value.replace(/[\u4e00-\u9fa5]/g,'')"
            >
              <el-button
                slot="append"
                :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
                @click="searchClick"
              >
              </el-button>
            </el-input>
          </div>
          <div class="header_right">
            <el-button
              size="small"
              class="el_button"
              icon="el-icon-plus"
              @click="addClick"
              style="margin-left: 20px"
              v-permission="{ action: 'device:childAdd' }"
              >添加</el-button
            >
            <!--  v-permission="{ action: 'device:add' }" -->

            <!-- <el-button
            class="el_button"
            size="small"
            icon="el-icon-upload2"
            style="margin-left: 15px"
            @click="onExports"
          >
            导出
          </el-button> -->
            <!--  v-permission="{ action: 'device:export' }" -->
          </div>
        </div>
        <div
          class="content"
          v-loading="loadingData"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(47, 51, 73, 0.3)"
          element-loading-text="拼命加载中"
        >
          <el-table
            :data="dataList"
            max-height="400px"
            class="table"
            ref="refTable"
            row-key="id"
            :header-cell-style="headerStyle"
            @selection-change="batchSelect"
          >
            <!-- <el-table-column
            align="center"
            type="selection"
            :reserve-selection="true"
            width="45"
          ></el-table-column> -->
            <!-- <el-table-column
            align="center"
            label="序号"
            type="index"
            width="50"
            v-if="headerList[0].flag"
          >
          </el-table-column> -->
            <el-table-column
              align="center"
              prop="imei"
              label="设备编码"
              min-width="180"
              show-overflow-tooltip
              v-if="headerList[1].flag"
            >
            </el-table-column>

            <el-table-column
              align="center"
              prop="online"
              label="位置标记"
              min-width="90"
              v-if="headerList[3].flag"
            >
              <template slot-scope="scope">
                <i
                  class="el-icon-success"
                  v-if="scope.row.mark != ''"
                  style="color: #28c76f; cursor: pointer"
                  @click="updateMark(scope.row)"
                ></i>
                <i
                  class="el-icon-error"
                  v-else
                  style="color: #f84242; cursor: pointer"
                  @click="updateMark(scope.row)"
                ></i>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="online"
              label="设备状态"
              min-width="90"
              v-if="headerList[4].flag"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.deviceType == 'Camera'">-</span>
                <el-tag
                  type="success"
                  size="mini"
                  v-else-if="scope.row.online === 1"
                  >在线</el-tag
                >
                <el-tag type="danger" size="mini" v-else>离线</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="isAlarm"
              label="告警状态"
              min-width="90"
              v-if="headerList[5].flag"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.deviceType == 'Camera'">-</span>
                <el-tag
                  type="success"
                  size="mini"
                  v-else-if="scope.row.isAlarm === 0"
                  >正常</el-tag
                >
                <el-tag type="danger" size="mini" v-else>告警</el-tag>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="batteryValue"
              label="电量"
              min-width="90"
              show-overflow-tooltip
              v-if="headerList[6].flag"
            >
              <template slot-scope="{ row }">
                <span
                  v-if="
                    row.batteryValue === '' ||
                    row.batteryValue == null ||
                    row.classMark == 'V380'
                  "
                  >-</span
                >
                <el-tag
                  type="success"
                  size="mini"
                  v-else-if="row.batteryValue >= 30"
                  >{{ row.batteryValue }}</el-tag
                >
                <el-tag type="danger" size="mini" v-else>{{
                  row.batteryValue
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="signalValue"
              label="信号"
              min-width="90"
              show-overflow-tooltip
              v-if="headerList[7].flag"
            >
              <template slot-scope="{ row }">
                <el-tag type="success" size="mini" v-if="row.signalValue == 0"
                  >优</el-tag
                >
                <el-tag
                  type="warning"
                  size="mini"
                  v-else-if="row.signalValue == 1"
                  >良</el-tag
                >
                <el-tag
                  type="danger"
                  size="mini"
                  v-else-if="row.signalValue == 2"
                  >差</el-tag
                >
                <span
                  v-else-if="row.signalValue == '' || row.signalValue == null"
                  >-</span
                >
                <el-tag type="danger" size="mini" v-else>差</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="isDefence"
              min-width="140"
              label="布防状态"
              show-overflow-tooltip
              v-if="headerList[11].flag"
            >
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isDefence == 0" type="warning"
                  >已撤防</el-tag
                >
                <el-tag v-else type="success">已布防</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="installTime"
              label="安装时间"
              min-width="160"
              show-overflow-tooltip
              v-if="headerList[12].flag"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="validity"
              label="到期状态"
              min-width="120"
              show-overflow-tooltip
              v-if="headerList[13].flag"
            >
              <template slot-scope="scope">
                <el-tag
                  type="success"
                  size="mini"
                  v-if="scope.row.validity === 0"
                  >未到期</el-tag
                >
                <el-tag type="danger" size="mini" v-else>已到期</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="inDate"
              label="有效期限（月）"
              min-width="120"
              show-overflow-tooltip
              v-if="headerList[14].flag"
            >
              <template slot-scope="scope">
                <el-tag type="success" size="mini" v-if="scope.row.inDate == 0"
                  >无期限</el-tag
                >
                <el-tag type="danger" size="mini" v-else>{{
                  scope.row.inDate
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="validityTime"
              label="到期时间"
              min-width="160"
              show-overflow-tooltip
              v-if="headerList[15].flag"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="remark"
              label="安装备注"
              min-width="100"
              show-overflow-tooltip
              v-if="headerList[16].flag"
            >
            </el-table-column>
            <el-table-column
              align="center"
              prop="management"
              label="操作"
              width="150"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="撤防时段"
                  placement="bottom"
                  v-permission="{ action: 'device:childTime' }"
                >
                  <i
                    @click="timeClick(row)"
                    class="iconfont shijian tableBtnIcon"
                  ></i>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="告警"
                  placement="bottom"
                  v-permission="{ action: 'device:childAlarm' }"
                >
                  <i
                    @click="alarmClick(row)"
                    class="iconfont gaojing tableBtnIcon"
                  ></i>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="拆除"
                  placement="bottom"
                  v-permission="{ action: 'device:childDelete' }"
                >
                  <i
                    @click="delClick(row.id)"
                    class="iconfont shanchu tableBtnIcon"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            :page.sync="page"
            :limit.sync="limit"
            :total="total"
            @pagination="getDataList"
            class="pagination"
          >
          </pagination>
        </div>
      </div>
    </el-dialog>

    <!-- 添加子设备 -->
    <ChildDeviceAdd ref="refChildDeviceAdd" :deviceInfo="deviceInfo" />

    <!-- 撤防时段 -->
    <EditTime ref="refeditTime" :deviceInfo="deviceInfoChild" />

    <!-- 告警 -->
    <Alarm ref="refAlarm" :deviceInfo="deviceInfoChild" />

    <!-- 位置标记 -->

    <Ichnography ref="refIchnography" :editId="editId" />
  </div>
</template>

<script>
import {
  reqDeviceList,
  reqDeviceUserunBind,
  reqProductList,
  reqDeviceUnBindByFather,
  reqOrgList,
  reqBatchCommand,
  reqFloorById,
  reqDeviceTask,
  reqCommandServicePage,
} from "@/api/api";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import ChildDeviceAdd from "@/views/deviceList/components/childDevice/Add.vue";
import Alarm from "../../components/childDevice/Alarm.vue";
import EditTime from "../../components/editTime.vue";
import Ichnography from "../Ichnography.vue";
export default {
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    Pagination,
    ChildDeviceAdd,
    EditTime,
    Alarm,
    Ichnography,
  },
  mixins: [tableStyleMixin],
  data() {
    return {
      dialogVisible: false,
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      searchForm: {
        imei: "",
      },
      loadingSearch: false,
      deviceInfoChild: {}, //设备一条信息
      batchDataList: [], //批量操作勾选的数据
      flag: true,
      loadingData: false,
      flagIssued: true,
      flagalarm: true, //告警模式禁用
      idList: [],
      editId: "",
      show: false, //表头设置默认隐藏
      headerList: [
        {
          name: "序号",
          flag: true,
        },
        {
          name: "设备编码",
          flag: true,
        },
        {
          name: "安装点",
          flag: true,
        },
        {
          name: "位置标记",
          flag: true,
        },
        {
          name: "设备状态",
          flag: true,
        },
        {
          name: "告警状态",
          flag: true,
        },
        {
          name: "电量",
          flag: true,
        },
        {
          name: "信号",
          flag: true,
        },
        {
          name: "产品类型",
          flag: true,
        },
        {
          name: "产品型号",
          flag: true,
        },
        {
          name: "单位",
          flag: true,
        },
        {
          name: "布防状态",
          flag: true,
        },
        {
          name: "安装时间",
          flag: true,
        },
        {
          name: "到期状态",
          flag: false,
        },
        {
          name: "有效期限（月）",
          flag: false,
        },
        {
          name: "到期时间",
          flag: false,
        },
        {
          name: "安装备注",
          flag: false,
        },
      ],
      // 导出加筛选条件
      exportList: {
        imei: "",
        online: "",
        productId: "",
        orgId: "",
        minBattery: "",
        maxBattery: "",
        isAlarm: "",
        buildingId: "",
        validity: "",
        classMark: "",
        startTime: "",
        endTime: "",
        remark: "",
      },
      meterList: [],
      identifier: "",
      serviceType: "",
      serviceValue: "",
    };
  },
  computed: { ...mapState(["user"]) },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.getDataList();
      }
    },
  },
  mounted() {
    document.addEventListener("click", this.handleClickOutside);
  },
  // 避免内存泄漏
  beforeDestroy() {
    document.removeEventListener("click", this.handleClickOutside);
  },
  methods: {
    handleClickOutside(event) {
      // 判断点击是否在表头设置区域内
      const biaotouDiv = this.$el.querySelector(".biaotou_div");
      const elIconSetting = this.$el.querySelector(".el-icon-setting");
      if (
        (!biaotouDiv || !biaotouDiv.contains(event.target)) &&
        (!elIconSetting || !elIconSetting.contains(event.target))
      ) {
        this.show = false;
      }
    },
    async getDataList() {
      const res = await reqDeviceList(this.page, this.limit, {
        fatherId: this.deviceInfo.id,
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        imei: this.searchForm.imei,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      console.log(res);
      this.dataList = res.data.rows;
      this.total = res.data.total;
    },

    getInitDataList() {
      this.page = 1;
      this.limit = 10;
      this.getDataList();
      this.clearSelections(); //清除勾选的设备
    },
    //显隐设置
    ShowHidden(item) {
      item.flag = !item.flag;
    },
    onChange() {
      this.$nextTick(() => {
        this.$refs.refTable.doLayout(); //对 Table 进行重新布局。当 Table 或其祖先元素由隐藏切换为显示时，可能需要调用此方法
      });
      // 表头设置 :记住当前账号的设置 存储在本地浏览器
      let meterflag = true;
      this.meterList.forEach((item) => {
        if (item.id == this.user.userId) {
          meterflag = false;
          item.arr = this.headerList;
          return;
        }
      });
      if (meterflag) {
        // 本地浏览器第一次设置
        this.meterList.push({
          id: this.user.userId,
          arr: this.headerList,
        });
      }
      localStorage.setItem("meter", JSON.stringify(this.meterList));
    },
    //显隐表头
    Show() {
      this.show = !this.show;
    },
    // 查询
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.getDataList();
      this.loadingSearch = false;
      this.clearSelections();
    },
    // 清除请求
    clearOnline() {
      this.getInitDataList();
    },
    clearProductId() {
      this.getInitDataList();
    },
    clearImei() {
      this.getInitDataList();
    },
    // 新增
    addClick() {
      if (this.dataList.length >= 5)
        return this.$modal.notifyWarning("最多添加5台设备！");
      this.$refs.refChildDeviceAdd.dialogVisible = true;
      //   this.$refs.refAdd.getBuildList();
    },
    // 导出  设备筛选有几个字段，这个接口就要加几个字段
    async onExports() {
      const result = await this.$confirm(
        "此操作将导出设备安装信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;
      const res = await reqDeviceTask({
        tenantId: this.user.tenantId,
        taskName: this.user.tenantName + "设备安装信息",
        imei: this.exportList.imei,
        online: this.exportList.online,
        productId: this.exportList.productId,
        orgId: this.exportList.orgId,
        minBattery: this.exportList.minBattery,
        maxBattery: this.exportList.maxBattery,
        isAlarm: this.exportList.isAlarm,
        buildingId: this.exportList.buildingId,
        validity: this.exportList.validity,
        classMark: this.exportList.classMark,
        startTime: this.exportList.startTime,
        endTime: this.exportList.endTime,
        remark: this.exportList.remark,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("导出成功");
      this.$router.push({ name: "exportTask" });
    },

    alarmClick(row) {
      this.$refs.refAlarm.dialogVisible = true;
      this.deviceInfoChild = JSON.parse(JSON.stringify(row));
    },

    timeClick(row) {
      // console.log(row);
      this.deviceInfoChild = JSON.parse(JSON.stringify(row));
      this.$refs.refeditTime.dialogVisible = true;
    },

    // 修改标记点
    async updateMark(e) {
      // console.log(e);
      this.editId = e.id;
      // 获取平面图 图片
      const res = await reqFloorById(e.spaceId);
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (res.data.rows.image == "")
        return this.$modal.notifyWarning("当前楼层暂无平面图,请上传后操作!");
      this.$refs.refIchnography.getimage(res.data.rows.image);
      this.$refs.refIchnography.dialogVisible = true;
      if (e.mark != "") {
        this.$refs.refIchnography.getMark(e.mark);
      }
    },

    // 解绑
    async delClick(id) {
      const result = await this.$confirm(
        "此操作将拆除该设备, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (result !== "confirm") return;
      this.reqDelFun(id);
    },
    // 点击复选框触发，可跨分页选择
    batchSelect(arr) {
      // console.log(arr);
      let type = "";
      arr.forEach((item, index) => {
        // console.log(item,index);
        if (index == 0) {
          type = item.deviceType; //判断是不是同一种类型
        }
        //先判断是不是同一种类型
        if (item.deviceType != type) {
          // console.log(111);
          this.flagIssued = true;
          return;
        } else {
          if (
            item.deviceType == "Infrared" ||
            item.deviceType == "SmokeAlarm"
          ) {
            // console.log(222);
            this.flagIssued = false;
          } else {
            this.flagIssued = true;
          }
          if (item.deviceType == "DoorMagnetism") {
            this.flagalarm = false;
          } else {
            this.flagalarm = true;
          }
        }
      });
      this.batchDataList = arr;
    },

    // 清空复选框√√
    clearSelections() {
      this.flagalarm = true;
      this.flagIssued = true;
      this.$refs.refTable.clearSelection();
    },
    // 请求解绑
    async reqDelFun(id) {
      const res = await reqDeviceUnBindByFather({
        id,
        userId: this.user.userId,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("拆除成功");
      this.getInitDataList();
    },
    onAdd() {
      this.$refs.refAdd.dialogVisible = true;
    },
    // 点击关闭弹框
    closeDialog() {
      this.searchForm.imei = "";
      this.dataList = [];
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../../views/common.less");
@import url("~@views/style/tablePage.less");

.common-container {
  // height: calc(100vh - 212px);
  height: calc(100vh - 27vh);
  overflow: auto;
  width: 100%;
}

.content {
  height: 500px;
}

.header {
  display: flex;
  justify-content: space-between;

  .left {
    font-size: 15px;
    color: @primaryTxtcolor;
    margin-bottom: 20px;

    // display: flex;
    // justify-content: center;
    .label {
      margin: 10px 0px;

      .name {
        font-size: 16px;
      }
    }
  }

  .right {
    margin-right: 10px;
  }
}

.el_button.el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

.tableBtnIcon {
  font-size: 23px !important;
}
</style>